package com.ancai.studentmenage;

import java.util.List;

import net.sf.json.JSON;
import net.sf.json.JSONObject;

import com.ancai.service.HttpService;
import com.ancai.util.CommonString;
import com.sms.user.bean.UserBean;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
	/**
	 * A dummy authentication store containing known user names and passwords.
	 * TODO: remove after connecting to a real authentication system.
	 */
	private static final String[] DUMMY_CREDENTIALS = new String[] {
			"foo@example.com:hello", "bar@example.com:world" };

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String mEmail;
	private String mPassword;

	// UI references.
	private EditText mEmailView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private ImageView mLoginImageView;
	Button mLoginBtn;
	String username;
	String pass;
	AnimationDrawable anim=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);

		// Set up the login form.
		mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
		mEmailView = (EditText) findViewById(R.id.userid);
		mEmailView.setText(mEmail);

		mPasswordView = (EditText) findViewById(R.id.password);
		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginImageView=(ImageView) findViewById(R.id.imageView1);
		mLoginBtn=(Button) findViewById(R.id.sign_in_button);
		doAnimation(mLoginImageView);
		addlistener();
	}

	private void addlistener(){
		mLoginBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				username=mEmailView.getText().toString().trim();
				pass=mPasswordView.getText().toString().trim();
				UserLoginTask uTask=new UserLoginTask();
				uTask.execute("do_login");
			}
		});
	}
	private void doAnimation(ImageView imageView){
		imageView.setBackgroundResource(R.drawable.login_animation);
		 anim = (AnimationDrawable) imageView.getBackground();
	}
	
	public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            anim.stop();
            anim.start();
            return true;
        }
        return super.onTouchEvent(event);
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}


	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<String, String, String> {

		@Override
		protected void onPostExecute(String result) {
			JSONObject jsonObject=JSONObject.fromObject(result);
			String err=jsonObject.getString("err");
			if(err.equals("-1")){
				String loginfo=jsonObject.getString("result");
				UserBean userBean= com.alibaba.fastjson.JSON.parseObject(loginfo,UserBean.class);
				if(userBean!=null){
					Intent it=new Intent(LoginActivity.this, MainActivity.class);
					Bundle bundle=new Bundle();
					bundle.putSerializable("userbean", userBean);
					it.putExtra("bundle", bundle);
					startActivity(it);
					LoginActivity.this.finish();
				}
			}else {
				Toast.makeText(LoginActivity.this, "用户名或登录密码错误", Toast.LENGTH_LONG).show();
			}
			
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(true);
		}

		@Override
		protected String doInBackground(String... params) {
			String result="";
			if(params[0].equals("do_login")){
				 String login_url=CommonString.DATA_URL+"sms/user/androidLogin.action?userid="+username+"&pass="+pass;
				  result=HttpService.getJson(login_url);
			}
			return result;
		}
	}
}
